class PlanController {

  def index = { redirect(action: list, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 30, 100)
    params.sort = 'id'
    params.order = 'asc'
    [planInstanceList: Plan.list(params), planInstanceTotal: Plan.count()]
  }

  def show = {
    def planInstance = Plan.get(params.id)

    if (!planInstance) {
      flash.message = "Plan not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [planInstance: planInstance] }
  }

  def delete = {
    def planInstance = Plan.get(params.id)
    if (planInstance) {
      try {
        planInstance.delete()
        flash.message = "Plan ${params.id} deleted"
        redirect(action: list)
      }
      catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "Plan ${params.id} could not be deleted"
        redirect(action: show, id: params.id)
      }
    }
    else {
      flash.message = "Plan not found with id ${params.id}"
      redirect(action: list)
    }
  }

  def edit = {
    def planInstance = Plan.get(params.id)

    if (!planInstance) {
      flash.message = "Plan not found with id ${params.id}"
      redirect(action: list)
    }
    else {
      return [planInstance: planInstance]
    }
  }

  def preview = {
    def planInstance = Plan.get(params.id)
    [planInstance: planInstance, baby:Baby.get(4)]
  }


  def ajaxpublish = {
    def planInstance = Plan.get(params.id)
    planInstance.published = planInstance.published ? !planInstance.published : true
    planInstance.save()
    if (planInstance.published) {
      if (planInstance.content) {
        def todir = grailsApplication.config.planTemplatePath
        //def pathname = servletContext.getRealPath("/WEB-INF/grails-app/views/page/${template.topic.name}")
        def pathname = todir + "planpage"
        def path = new File(pathname)
        if (!path.exists()) {
          path.mkdirs()
        }
        def file = new File(pathname + "/_${planInstance.id}.gsp")
        if (file.exists()) {
          file.delete()
        }
        file.createNewFile()
        file << planInstance.content
      }
      render '1'
    } else {
      render '0'
    }
  }
  def publish = {
    def planInstance = Plan.get(params.id)
    planInstance.published = true
    if (params.published) {
      planInstance.published = params.published.toBoolean()
    }
    planInstance.save()
    if (planInstance.content) {
      def todir = grailsApplication.config.planTemplatePath
      //def pathname = servletContext.getRealPath("/WEB-INF/grails-app/views/page/${template.topic.name}")
      def pathname = todir + "planpage"
      def path = new File(pathname)
      if (!path.exists()) {
        path.mkdirs()
      }
      def file = new File(pathname + "/_${planInstance.id}.gsp")
      if (file.exists()) {
        file.delete()
      }
      file.createNewFile()
      file << planInstance.content
    }
    if (planInstance.published) {
      render '1'
    } else {
      render '0'
    }
  }

  def update = {
    def planInstance = Plan.get(params.id)
    if (planInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (planInstance.version > version) {

          planInstance.errors.rejectValue("version", "plan.optimistic.locking.failure", "Another user has updated this Plan while you were editing.")
          render(view: 'edit', model: [planInstance: planInstance])
          return
        }
      }
      planInstance.properties = params
      planInstance.published = false
      if (!planInstance.hasErrors() && planInstance.save()) {
        if (planInstance.content) {
          def todir = grailsApplication.config.planTemplatePath
          //def pathname = servletContext.getRealPath("/WEB-INF/grails-app/views/page/${template.topic.name}")
          def pathname = todir + "planpage/prev"
          def path = new File(pathname)
          if (!path.exists()) {
            path.mkdirs()
          }
          def file = new File(pathname + "/_${planInstance.id}.gsp")
          if (file.exists()) {
            file.delete()
          }
          file.createNewFile()
          file << planInstance.content
        }

        flash.message = "Plan ${params.id} updated"
        redirect(action: show, id: planInstance.id)
      }
      else {
        render(view: 'edit', model: [planInstance: planInstance])
      }
    }
    else {
      flash.message = "Plan not found with id ${params.id}"
      redirect(action: edit, id: params.id)
    }
  }

  def create = {
    def planInstance = new Plan()
    planInstance.properties = params
    return ['planInstance': planInstance]
  }

  def save = {
    def planInstance = new Plan(params)
    planInstance.published = false
    if (!planInstance.hasErrors() && planInstance.save()) {
      if (planInstance.content) {
        def todir = grailsApplication.config.planTemplatePath
        //def pathname = servletContext.getRealPath("/WEB-INF/grails-app/views/page/${template.topic.name}")
        def pathname = todir + "planpage/prev"
        def path = new File(pathname)
        if (!path.exists()) {
          path.mkdirs()
        }
        def file = new File(pathname + "/_${planInstance.id}.gsp")
        if (file.exists()) {
          file.delete()
        }
        file.createNewFile()
        file << planInstance.content
      }
      flash.message = "Plan ${planInstance.id} created"
      redirect(action: show, id: planInstance.id)
    }
    else {
      render(view: 'create', model: [planInstance: planInstance])
    }
  }

  def synch = {
    def plan = Plan.get(params.id)
    if (plan) {
      def taskList = Task.findAllByPlanId(plan.id)
      taskList.each {
        it.content = plan.description
        it.save()
      }
    }
    render "finished."
  }

}
